package vn.cuhanh.fragment;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.cuhanh.MainActivity;
import vn.cuhanh.R;
import vn.cuhanh.ShareActivity;
import vn.cuhanh.bean.Account;
import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.utils.HelperFunc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class LeaderBoardFragment extends BasicFragment {
	
	private ArrayList<Account> bxhUserList = new ArrayList<Account>();
	LeaderBoardListAdapter adapter;
	public final int ITEM_PER_PAGE = 10;
	public boolean haveMoreData = true;
	public int currentPage = 0;
	private View view;
	private PullToRefreshListView listViewBXH;

	public static LeaderBoardFragment newInstance(Context ctx) {
		return new LeaderBoardFragment(ctx);
	}

	public LeaderBoardFragment(Context ctx) {
		super(ctx);
	}

	public LeaderBoardFragment() {
		super();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onPause() {
		super.onPause();
		// HelperFunc.unbindDrawables(view);
		// System.gc();
	}

	@Override
	public void onDestroy() {

		super.onDestroy();
	}
	
	public void loadData(){
		loadData(1);
		return;
	}
	
	public void loadData(int page){
		if(currentPage >= page) {
			return;
		}
		currentPage = page;
		final String url = ctx.getResources().getString(R.string.getLeaderBoard).replace("user_name", MainActivity.username) + page;
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String response = HelperFunc.getDataFromSv(url);
					if(listViewBXH != null) {
						((Activity)ctx).runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								listViewBXH.onRefreshComplete();
							}
						});
					}
					if(response == null) {
						return;
					}
					JSONObject jsonResponse = new JSONObject(response);
					Log.d("leaderboard", response);
					int result = jsonResponse.getInt("result");
					if(result != 1) {
						return;
					}
					try {
						if(jsonResponse.has("rank")) {
							MainActivity.userAccount.setRank(jsonResponse.getInt("rank"));
						}
					} catch (Exception ex) {
						HelperFunc.readStackTrace(ex);
					}
					
					JSONArray users = jsonResponse.getJSONArray("data");
					if(users.length() == 0) {
						return;
					}
					for(int i = 0; i < users.length(); i++) {
						JSONObject u = users.getJSONObject(i);
						Account acc = new Account(1 , u.getString("userName"), u.getString("charName"), u.getInt("score"), bxhUserList.size() + 1);
						bxhUserList.add(acc);
					}
					((Activity)ctx).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							adapter.notifyDataSetChanged();
							TextView txtRank = (TextView) view.findViewById(R.id.leader_board_rank);
							txtRank.setText(ctx.getResources().getString(R.string.bxh_charinfo_rank) + ": " + String.valueOf(MainActivity.userAccount.getRank()));
						}
					});
				} catch (Exception e) {
					HelperFunc.readStackTrace(e);
				}
			}
		});
		thread.start();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		try {
			view = inflater.inflate(R.layout.leaderboard, null);
			if (ctx == null || view == null) {
				if (isAdded()) {
					ctx = getActivity();
				} else {
					return view;
				}
			}
			listViewBXH = (PullToRefreshListView) view.findViewById(R.id.bxh_list);
			adapter = new LeaderBoardListAdapter(ctx, R.layout.leaderboard_list_item);
			
			TextView txtDndScore = (TextView) view.findViewById(R.id.leader_board_dnd);
			int dndScore = 0;
			if(MainActivity.userAccount != null) {
				dndScore = MainActivity.userAccount.getDndScore();
			}
			txtDndScore.setText(ctx.getResources().getString(R.string.diem_nang_dong_viet_tat) + ": " + String.valueOf(dndScore));
			TextView txtCharName = (TextView) view.findViewById(R.id.leader_board_display_name);
			txtCharName.setText(MainActivity.userAccount.getCharName());
			TextView txtUserName = (TextView) view.findViewById(R.id.leader_board_user_name);
			txtUserName.setText(ctx.getResources().getString(R.string.userName) + " " + MainActivity.username);
			TextView txtRank = (TextView) view.findViewById(R.id.leader_board_rank);
			txtRank.setText(ctx.getResources().getString(R.string.bxh_charinfo_rank) + ": " + String.valueOf(MainActivity.userAccount.getRank()));
			ImageView avatar = (ImageView)view.findViewById(R.id.leader_board_avatar);
			try {
				if(MainActivity.userAccount != null) {
					avatar.setImageBitmap(HelperFunc.getBitmapFromAsset(this.ctx, this.ctx.getResources().getString(R.string.avatar_file_name).replace("number", String.valueOf(MainActivity.userAccount.getAvatarNumber()))));
				}
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			}
			
			View btnShare = view.findViewById(R.id.leader_board_btn_share);
			btnShare.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					HelperFunc.trackEvent(ctx, "share", "btn_share_press", "Share_leader_board_press");
					ShareActivity.shareInfo = new ShareInfo(
							ctx.getResources().getString(R.string.shareLeaderBoardTitle), 
							ctx.getResources().getString(R.string.shareLeaderBoardName), 
							ctx.getResources().getString(R.string.shareLeaderboardDescription)
								.replace("char_name", CharacterInfoFragment.getCharName())
								.replace("rank", String.valueOf(MainActivity.userAccount.getRank())), 
							ctx.getResources().getString(R.string.shareLeaderboardImageUrl), 
							ctx.getResources().getString(R.string.shareLeaderboardLocalImage), 
							ctx.getResources().getString(R.string.shareLeaderboardLink), 
							ctx.getResources().getString(R.string.shareLeaderBoardState),
							0);
					Intent intent = new Intent(ctx, ShareActivity.class);
					startActivity(intent);
				}
			});
			
			listViewBXH.setAdapter(adapter);
			listViewBXH.setMode(Mode.BOTH);
			listViewBXH.setOnRefreshListener(new OnRefreshListener2() {

				@Override
				public void onPullDownToRefresh(PullToRefreshBase refreshView) {
					// TODO Auto-generated method stub
					loadData(currentPage + 1);
				}

				@Override
				public void onPullUpToRefresh(PullToRefreshBase refreshView) {
					// TODO Auto-generated method stub
					loadData(currentPage + 1);
				}
			});
			//Use timer, delay loadData process in order to avoid exception:
			//java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. 
			//Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. 
			//[in ListView(16908298, class com.handmark.pulltorefresh.library.PullToRefreshListView$InternalListViewSDK9) 
			//with Adapter(class android.widget.HeaderViewListAdapter)]
			//This is just a work arround.
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					loadData();
				}
			}, (long)1000);
			return view;
		} catch (InflateException e) {
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
		return null;
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setRetainInstance(true);
	}
	
	public class LeaderBoardListAdapter extends ArrayAdapter<Account> {

		public LeaderBoardListAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public int getCount() {
			return bxhUserList.size();
		}
		
		@Override
		public View getView(int position, View v, ViewGroup parent) {
			if(v == null) {
				LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.leaderboard_list_item, null);
			}
			Account acc = bxhUserList.get(position);
			if(acc == null) {
				return v;
			}
			if(position % 2 == 0) {
				v.setBackgroundColor(0xFFFFFFFF);
			} else {
				v.setBackgroundColor(0xFFF9F9F9);
			}
			TextView txtRank = (TextView) v.findViewById(R.id.bxh_list_item_rank);
			txtRank.setText(String.valueOf(acc.getRank()));
			TextView txtName = (TextView) v.findViewById(R.id.bxh_list_item_name);
			txtName.setText(acc.getCharName());
			TextView txtScore = (TextView) v.findViewById(R.id.bxh_list_item_dnd);
			txtScore.setText(String.valueOf(acc.getDndScore()));
			return v;
		}
		
	}
}
